N = 10000;
nf = 1;

%% 1.1 Равномерность
fid = fopen( 'fib_seq.txt', 'r' );
num = zeros(1, N);
for i = 1:N
    num(i) = str2double(fgetl(fid));
end
fclose(fid);

m = 0.05;
[n, xout] = hist(num, 0:m:1);
n = n./N;
figure(nf);
nf = nf + 1;
subplot(1,1,1);
hold on
bar(xout, n);
plot(xout, ones(1,1/m + 1)*m);
axis([0, 1, 0, 0.1]);
hold off

%% 1.2 Равномерность
k = zeros(1, 10);
num = zeros(1, N);
for f = 1:10
    fid = fopen(sprintf('sequences\\%d.txt', f), 'r' );    
    for i = 1:N
        num(i) = str2double(fgetl(fid));
    end
    fclose(fid);
    res = num(1:2:N).^2 + num(2:2:N).^2;
    k(f) = 0;
    for i = 1:N/2
        if res(i) < 1
            k(f) = k(f) + 1;
        end
    end
end
figure(nf);
nf = nf + 1;
subplot(1,1,1);
plot(1:10, 2*k/N, 1:10, ones(1,10)*pi/4);

%% 2 Стохастичность
fid = fopen('fib_seq.txt', 'r');
num = zeros(1, N);
for i = 1:N
    num(i) = str2double(fgetl(fid));
end
fclose(fid);

bin = cell(1,N);
for i = 1:N
    bin{i} = dec2bin(num(i).*1000000);
end

figure(nf);
nf = nf + 1;
np = 1;
for l = 10:17
    n_t = zeros(1, l);
    n_p = zeros(1, l);
    for j = 1:l
        n_t(j) = N*nchoosek(l,j)*(0.5)^l;
        for i = 1:N     
            if length(find(find(bin{i} == '1') < l)) == j
                n_p(j) = n_p(j) + 1;   
            end
        end
    end
    subplot(2,4,np);
    np = np + 1;
    plot(1:l, n_t, 'r', 1:l, n_p, 'b');
    title(sprintf('%d', l));
end

%% 3 Независимость
fid1 = fopen('sequences\\1.txt', 'r');
fid2 = fopen('sequences\\2.txt', 'r');
num1 = zeros(1,N);
num2 = zeros(1,N);
for i = 1:N
    num1(i) = str2double(fgetl(fid1));
    num2(i) = str2double(fgetl(fid2));
end
fclose(fid1);
fclose(fid2);

tau = 0;
for i = 1:N
    tau = find(num2 == num1(i));
    if tau
        if (tau > i)
            [r, p] = corrcoef(num1(i:N-tau+i), num2(tau:N));        
        else
            [r, p] = corrcoef(num1(i:N), num2(tau:N-i+tau));
        end
        %%disp(p);
        if find(p < 0.05)
            fprintf('i = %d tau = %d\n', i, tau);            
        end
    end    
end
